"""
机器CRUD操作
"""
from sqlalchemy.orm import Session
from app.models.machine import Machine
from app.core.performance_monitor import monitor_db_performance
from typing import Optional, List

@monitor_db_performance("get_machine_by_id")
def get_machine_by_id(db: Session, machine_id: int) -> Optional[Machine]:
    """根据ID获取机器"""
    return db.query(Machine).filter(Machine.id == machine_id).first()

@monitor_db_performance("get_machine_by_ip")
def get_machine_by_ip(db: Session, ip: str) -> Optional[Machine]:
    """根据IP获取机器"""
    return db.query(Machine).filter(Machine.ip == ip).first()

@monitor_db_performance("get_machines")
def get_machines(db: Session, skip: int = 0, limit: int = 100) -> List[Machine]:
    """获取机器列表"""
    return db.query(Machine).offset(skip).limit(limit).all()

@monitor_db_performance("get_machines_by_status")
def get_machines_by_status(db: Session, status: str) -> List[Machine]:
    """根据状态获取机器列表"""
    return db.query(Machine).filter(Machine.status == status).all()

@monitor_db_performance("create_machine")
def create_machine(db: Session, machine_data: dict) -> Machine:
    """创建机器"""
    db_machine = Machine(**machine_data)
    db.add(db_machine)
    db.commit()
    db.refresh(db_machine)
    return db_machine

@monitor_db_performance("update_machine")
def update_machine(db: Session, machine_id: int, machine_data: dict) -> Optional[Machine]:
    """更新机器信息"""
    db_machine = get_machine_by_id(db, machine_id)
    if db_machine:
        for key, value in machine_data.items():
            setattr(db_machine, key, value)
        db.commit()
        db.refresh(db_machine)
    return db_machine

@monitor_db_performance("delete_machine")
def delete_machine(db: Session, machine_id: int) -> bool:
    """删除机器(软删除)"""
    db_machine = get_machine_by_id(db, machine_id)
    if db_machine:
        setattr(db_machine, 'is_activate', False)
        db.commit()
        return True
    return False

@monitor_db_performance("update_machine_metrics")
def update_machine_metrics(db: Session, machine_id: int, cpu: int, memory: int, disk: int) -> Optional[Machine]:
    """更新机器监控指标"""
    db_machine = get_machine_by_id(db, machine_id)
    if db_machine:
        setattr(db_machine, 'cpu', cpu)
        setattr(db_machine, 'memory', memory)
        setattr(db_machine, 'disk', disk)
        # 根据使用率更新状态
        if cpu > 90 or memory > 90 or disk > 90:
            setattr(db_machine, 'status', 'warning')
        elif cpu < 10 and memory < 10 and disk < 10:
            setattr(db_machine, 'status', 'offline')
        else:
            setattr(db_machine, 'status', 'online')
        db.commit()
        db.refresh(db_machine)
    return db_machine